package us.webone.webone.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import us.webone.webone.entity.Favorite;
import us.webone.webone.service.IFavoriteService;

import java.util.List;
import java.util.Map;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author none
 * @since 2021-06-30
 */
@RestController
@RequestMapping("/api/favorite")
public class FavoriteController {

    IFavoriteService favoriteService;

    /**
     * 添加收藏
     */
    @PostMapping("/add")
    public ResponseEntity<String> addFavorite(@RequestBody Map<String, String> map, @CookieValue("id") Long userID) {
        String id = map.get("id");
        String website = map.get("website");
        String url = map.get("url");

        Favorite newFavorite = new Favorite();
        if (id != null) {
            newFavorite.setId(Long.parseLong(id));
        }
        newFavorite.setWebsite(website);
        newFavorite.setUrl(url);
        newFavorite.setUserId(userID);

        favoriteService.saveOrUpdate(newFavorite);
        return new ResponseEntity<>("添加成功", HttpStatus.OK);
    }

    /**
     * 删除收藏
     */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<String> deleteFavorite(@PathVariable("id") Long id, @CookieValue("id") Long userId) {
        QueryWrapper<Favorite> query = new QueryWrapper<>();
        query.eq("id", id).eq("userId", userId);
        favoriteService.remove(query);

        return new ResponseEntity<>("删除成功", HttpStatus.OK);
    }

    /**
     * 获取收藏
     */
    @GetMapping("/get")
    public ResponseEntity<List<Favorite>> getFavorite(@CookieValue("id") Long userId) {
        QueryWrapper<Favorite> query = new QueryWrapper<>();
        query.eq("userId", userId);
        List<Favorite> list = favoriteService.list(query);

        return new ResponseEntity<>(list, HttpStatus.OK);
    }
}